﻿import 'package:azring/services/device_sn_manager.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:characters/characters.dart';
import '../../../gen/assets.gen.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../core/repository/default_api.dart';
import 'year_calendar_view.dart';

/// 日历页面
class CalendarView extends StatefulWidget {
  const CalendarView({super.key});

  @override
  State<CalendarView> createState() => _CalendarViewState();
}

class _CalendarViewState extends State<CalendarView> {
  DateTime _currentDate = DateTime.now();
  Map<String, Map<String, dynamic>> _signDataMap = {}; // 存储签文数据，key为日期字符串
  bool _isLoading = false;
  DateTime? _selectedDate; // 当前选中的日期
  Map<String, dynamic>? _selectedSignData; // 当前选中日期的签文数据

  @override
  void initState() {
    super.initState();
    _loadSignData();
  }

  /// 加载签文数据
  Future<void> _loadSignData() async {
    setState(() {
      _isLoading = true;
    });

    final deviceSnManager = Get.find<DeviceSnManager>();
     

    try {
      final response = await DefaultApi().queryRingTodaySignListGet<dynamic>(
         deviceSn:  deviceSnManager.getDeviceSn(),
        isShowLoading: false,
      );

      if (response != null && response is Map && response['data'] != null) {
        final List<dynamic> dataList = response['data'] as List<dynamic>;
        final Map<String, Map<String, dynamic>> tempMap = {};

        for (var item in dataList) {
          if (item is Map<String, dynamic>) {
            final dailyValue = item['dailyValue'] as String?;
            if (dailyValue != null) {
              tempMap[dailyValue] = item;
            }
          }
        }

        setState(() {
          _signDataMap = tempMap;
        });
      }
    } catch (e) {
      print('加载签文数据失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 顶部渐变背景
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            height: 300.h,
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topRight,
                  end: Alignment.bottomRight,
                  colors: ThemeManager.to.backgroundGradientColors,
                  stops: const [0.1, 0.3, 0.7, 1.0],
                ),
              ),
            ),
          ),
          // 内容区域
          SafeArea(
            child: Column(
              children: [
                // 自定义AppBar
                _buildCustomAppBar(),
                // 可滚动内容区域
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        // 日历内容
                        Container(
                          height: 370.h,
                          margin: EdgeInsets.all(11.w),
                          decoration: BoxDecoration(
                            border: Border.all(
                                width: 1, color: const Color(0xff212121)),
                            borderRadius: BorderRadius.circular(20.r),
                          ),
                          child: Column(
                            children: [
                              // 星期标题
                              Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 16.w, vertical: 10.h),
                                child: Row(
                                  children: [
                                    '周一',
                                    '周二',
                                    '周三',
                                    '周四',
                                    '周五',
                                    '周六',
                                    '周日'
                                  ]
                                      .map((day) => Expanded(
                                            child: Center(
                                              child: Text(
                                                day,
                                                style: TextStyle(
                                                  color: Colors.white
                                                      .withOpacity(0.7),
                                                  fontSize: 14.sp,
                                                  fontWeight: FontWeight.w400,
                                                ),
                                              ),
                                            ),
                                          ))
                                      .toList(),
                                ),
                              ),
                              // 日历网格
                              Expanded(
                                child: _isLoading
                                    ? const Center(
                                        child: CircularProgressIndicator(
                                          color: Color(0xffF46425),
                                        ),
                                      )
                                    : _buildCalendarGrid(),
                              ),
                            ],
                          ),
                        ),
                        // 签文详情区域
                        if (_selectedSignData != null) _buildSignDetailCard(),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建自定义AppBar
  Widget _buildCustomAppBar() {
    return Container(
      height: 56.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          // 返回按钮
          IconButton(
            icon: const Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
              size: 20,
            ),
            onPressed: () => Get.back(),
          ),
          // 中间标题区域
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 左侧月份导航按钮
                IconButton(
                  onPressed: _previousMonth,
                  icon: Assets.status.preMonth.image(
                    width: 24.w,
                    height: 24.w,
                  ),
                ),
                SizedBox(width: 16.w),
                // 中间年份月份显示
                Text(
                  '${_currentDate.year}年${_currentDate.month}月',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                SizedBox(width: 16.w),
                // 右侧月份导航按钮
                IconButton(
                  onPressed: _nextMonth,
                  icon: Assets.status.nextMonth.image(
                    width: 24.w,
                    height: 24.w,
                  ),
                ),
              ],
            ),
          ),
          // 右侧日历图标
          GestureDetector(
            onTap: _onYearCalendarTap,
            child: Assets.status.yearCalendar.image(
              width: 24.w,
              height: 24.w,
              color: const Color(0xffF46425),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCalendarGrid() {
    final firstDayOfMonth = DateTime(_currentDate.year, _currentDate.month, 1);
    final lastDayOfMonth =
        DateTime(_currentDate.year, _currentDate.month + 1, 0);
    final firstWeekday = firstDayOfMonth.weekday; // 1=周一, 7=周日
    final daysInMonth = lastDayOfMonth.day;

    // 创建日历网格数据
    final List<DateTime?> dates = [];

    // 添加空白占位符（当月第一天之前的空位）
    for (int i = 1; i < firstWeekday; i++) {
      dates.add(null);
    }

    // 添加当月的日期
    for (int i = 1; i <= daysInMonth; i++) {
      dates.add(DateTime(_currentDate.year, _currentDate.month, i));
    }

    return GridView.builder(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 4.h),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 7,
        childAspectRatio: 1.0,
        crossAxisSpacing: 4.w,
        mainAxisSpacing: 6.h,
      ),
      itemCount: dates.length,
      itemBuilder: (context, index) {
        final date = dates[index];

        // 如果是空白占位符，返回空容器
        if (date == null) {
          return Container();
        }

        final isToday = _isToday(date);
        final signData = _getSignData(date);
        final hasData = signData != null;

        return GestureDetector(
          onTap: () => _onDateTap(date, signData),
          child: Container(
            decoration: BoxDecoration(
              color: hasData
                  ? const Color(0xffF46425).withOpacity(0.1)
                  : Colors.transparent,
              borderRadius: BorderRadius.circular(8.r),
              border: hasData
                  ? Border.all(color: const Color(0xffF46425), width: 1)
                  : null,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  date.day.toString(),
                  style: TextStyle(
                    color: isToday ? const Color(0xffF46425) : Colors.white,
                    fontSize: 10.sp,
                    fontWeight: isToday ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
                if (hasData) ...[
                  SizedBox(height: 2.h),
                  Text(
                    '${signData['statusScore'] ?? '--'}分',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 10.sp,
                    ),
                  ),
                  SizedBox(height: 1.h),
                  Container(
                    padding:
                        EdgeInsets.symmetric(horizontal: 4.w, vertical: 1.h),
                    decoration: BoxDecoration(
                      color: const Color(0xffF46425),
                      borderRadius: BorderRadius.circular(4.r),
                    ),
                    child: Text(
                      signData['lingTiao'] ?? '安康签',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 8.sp,
                      ),
                    ),
                  ),
                ],
              ],
            ),
          ),
        );
      },
    );
  }

  void _previousMonth() {
    setState(() {
      _currentDate = DateTime(_currentDate.year, _currentDate.month - 1);
    });
    _loadSignData(); // 重新加载数据
  }

  void _nextMonth() {
    setState(() {
      _currentDate = DateTime(_currentDate.year, _currentDate.month + 1);
    });
    _loadSignData(); // 重新加载数据
  }

  void _onDateTap(DateTime date, Map<String, dynamic>? signData) {
    // 更新选中的日期和签文数据
    setState(() {
      _selectedDate = date;
      _selectedSignData = signData;
    });
  }

  void _onYearCalendarTap() async {
    // 跳转到整年日历页面
    final result = await Get.to(() => const YearCalendarView());
    if (result != null && result is DateTime) {
      // 如果从整年日历返回了选中的月份，更新当前日期
      setState(() {
        _currentDate = result;
      });
      _loadSignData(); // 重新加载数据
    }
  }

  bool _isToday(DateTime date) {
    final now = DateTime.now();
    return date.year == now.year &&
        date.month == now.month &&
        date.day == now.day;
  }

  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }

  /// 获取指定日期的签文数据
  Map<String, dynamic>? _getSignData(DateTime date) {
    final dateStr =
        '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    return _signDataMap[dateStr];
  }

  /// 构建签文详情卡片（完全复用daily_check_in_view的样式）
  Widget _buildSignDetailCard() {
    if (_selectedSignData == null) return const SizedBox.shrink();

    final lingTiao = _selectedSignData!['lingTiao'] as String? ?? '';
    final sunPillar = _selectedSignData!['sunPillar'] as String? ?? '';
    final healthReviews = _selectedSignData!['healthReviews'] as String? ?? '';
    final healthAdvice = _selectedSignData!['healthAdvice'] as String? ?? '';
    final healthTraceability =
        _selectedSignData!['healthTraceability'] as String? ?? '';
    final funEasterEggs = _selectedSignData!['funEasterEggs'] as String? ?? '';

    return Container(
      height: 600.h, 
      margin: EdgeInsets.symmetric(horizontal: 11.w, vertical: 10.h),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 卡片背景图片
          Center(
            child: Container(
              width: double.infinity,
              height: double.infinity,
              padding: EdgeInsets.all(10.w),
              child: Stack(
                children: [
                  // textBg背景图片
                  Assets.signature.textBg.image(
                    width: double.infinity,
                    height: double.infinity,
                    fit: BoxFit.contain,
                  ),
                  Positioned(
                    top: 30.h,
                    left: 30.w,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 标题
                        Assets.signature.todayText.image(
                          width: 114.w,
                          fit: BoxFit.contain,
                        ),
                        SizedBox(height: 8.h),
                        // 日期
                        if (_selectedDate != null)
                          Text(
                            _formatSelectedDate(_selectedDate!),
                            style: TextStyle(
                              color: Colors.grey[400],
                              fontSize: 13.sp,
                            ),
                          ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          // 右上角装饰标签
          Positioned(
            top: -30.h,
            right: 20.w,
            child: SizedBox(
              width: 66.w,
              height: 196.h,
              child: Stack(
                children: [
                  // 装饰标签背景图片
                  Assets.signature.luckyBg.image(
                    width: 66.w,
                    height: 196.h,
                    fit: BoxFit.cover,
                  ),
                  // AZring图标
                  Positioned(
                    top: 40.h,
                    left: 15.w,
                    child: Assets.signature.aZring.image(
                      width: 36.w,
                      height: 7.h,
                      fit: BoxFit.cover,
                    ),
                  ),
                  // 灵条和日柱文字 - 竖着显示
                  Positioned(
                    top: 60.h,
                    left: 0,
                    right: 0,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        // 灵条 - 竖着显示
                        if (lingTiao.isNotEmpty)
                          Container(
                            margin: EdgeInsets.only(right: 8.w),
                            child: _buildVerticalText(
                              text: lingTiao,
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w500,
                              letterSpacing: 2.h,
                              strokeColor: const Color(0xFFFF6B35),
                              strokeWidth: 1.2,
                            ),
                          ),
                        // 日柱 - 竖着显示
                        if (sunPillar.isNotEmpty)
                          _buildVerticalText(
                            text: sunPillar,
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w500,
                            letterSpacing: 2.h,
                            strokeColor: const Color(0xFFFF6B35),
                            strokeWidth: 1.2,
                          ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          // 内容区域
          Center(
            child: Container(
              width: double.infinity,
              height: double.infinity,
              padding: EdgeInsets.only(top: 50.w),
              child: Stack(
                children: [
                  // 外层背景 - innerbg
                  Center(
                    child: Assets.signature.innerBg.image(
                      width: double.infinity,
                      height: double.infinity,
                      fit: BoxFit.contain,
                    ),
                  ),
                  // 内层背景 - innerbg2
                  Center(
                    child: Assets.signature.innerBg2.image(),
                  ),
                  // 内容文字 - 添加滚动支持
                  Positioned.fill(
                    top: 70.w,
                    left: 40.w,
                    right: 40.w,
                    bottom: 30.h,
                    child: SingleChildScrollView(
                      physics: const BouncingScrollPhysics(),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 健康评语
                          _buildSection(
                            title: '健康评语',
                            content: [healthReviews],
                          ),
                          _buildSeparator(),
                          _buildSection(
                            title: '健康建议',
                            content: [healthAdvice],
                          ),
                          _buildSeparator(),
                          // 健康溯源
                          _buildSection(
                            title: '健康溯源',
                            content: [healthTraceability],
                          ),
                          _buildSeparator(),
                          _buildSection(
                            title: '趣味彩蛋',
                            content: [funEasterEggs],
                          ),
                          SizedBox(height: 20.h), // 底部留白
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建内容区块
  Widget _buildSection({
    required String title,
    required List<String> content,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: TextStyle(
            color: const Color(0xffF9F8F7),
            fontSize: 15.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(height: 8.h),
        ...content.map((text) => text.isEmpty
            ? const SizedBox.shrink()
            : Padding(
                padding: EdgeInsets.only(bottom: 4.h),
                child: Text(
                  text,
                  style: TextStyle(
                    color: const Color(0xff797676),
                    fontSize: 13.sp,
                    height: 1.5,
                  ),
                ),
              )),
      ],
    );
  }

  /// 构建竖排文本（逐字竖排，保持正向）
  Widget _buildVerticalText({
    required String text,
    required Color color,
    required double fontSize,
    required FontWeight fontWeight,
    double letterSpacing = 2.0,
    Color? strokeColor,
    double strokeWidth = 1.0,
  }) {
    final Characters chars = text.characters;
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: chars
          .map((String ch) => Padding(
                padding: EdgeInsets.only(bottom: letterSpacing),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    if (strokeColor != null)
                      Text(
                        ch,
                        style: TextStyle(
                          foreground: Paint()
                            ..style = PaintingStyle.stroke
                            ..strokeWidth = strokeWidth
                            ..color = strokeColor,
                          fontSize: fontSize,
                          fontWeight: fontWeight,
                          height: 1.0,
                        ),
                      ),
                    Text(
                      ch,
                      style: TextStyle(
                        color: color,
                        fontSize: fontSize,
                        fontWeight: fontWeight,
                        height: 1.0,
                      ),
                    ),
                  ],
                ),
              ))
          .toList(),
    );
  }

  /// 构建分隔线
  Widget _buildSeparator() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 12.h),
      height: 1.h,
      color: const Color(0xffC89A8E).withOpacity(0.2),
    );
  }

  /// 格式化选中的日期
  String _formatSelectedDate(DateTime date) {
    return '${date.year}年${date.month}月${date.day}日';
  }
}
